import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/note_provider.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_button.dart';
import '../../widgets/platform/responsive_layout.dart';
import 'package:go_router/go_router.dart';
import '../../../domain/entities/note.dart';
// 添加请求实体导入
import '../../../core/offline/offline_mode_manager.dart'; // 添加离线模式管理器

/// 笔记列表页面
class NoteListPage extends ConsumerStatefulWidget {
  const NoteListPage({super.key});

  @override
  ConsumerState<NoteListPage> createState() => _NoteListPageState();
}

class _NoteListPageState extends ConsumerState<NoteListPage> {
  final TextEditingController _searchController = TextEditingController();
  List<String> _selectedTags = [];

  @override
  void initState() {
    super.initState();
    // 加载笔记列表
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(noteStateProvider.notifier).loadNotes();
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final noteState = ref.watch(noteStateProvider);
    final notes = ref.watch(notesProvider);
    final offlineStatus = ref.watch(offlineModeStatusProvider); // 监听离线状态

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('我的笔记'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          // 显示离线状态指示器
          if (offlineStatus != OfflineModeStatus.online)
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                decoration: BoxDecoration(
                  color: offlineStatus == OfflineModeStatus.offline
                      ? Colors.red
                      : Colors.orange,
                  borderRadius: BorderRadius.circular(12.0),
                ),
                child: Row(
                  children: [
                    Icon(
                      offlineStatus == OfflineModeStatus.offline
                          ? Icons.cloud_off
                          : Icons.cloud_sync,
                      size: 16,
                      color: Colors.white,
                    ),
                    const SizedBox(width: 4),
                    SelectableText(
                      offlineStatus == OfflineModeStatus.offline ? '离线' : '同步中',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              ref.read(noteStateProvider.notifier).loadNotes();
            },
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              // 跳转到创建笔记页面
              context.push('/admin/notes/create');
            },
          ),
        ],
      ),
      body: Column(
        children: [
          // 搜索栏
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _searchController,
              decoration: const InputDecoration(
                hintText: '搜索笔记...',
                prefixIcon: Icon(Icons.search),
                border: OutlineInputBorder(),
              ),
              onSubmitted: (value) {
                ref.read(noteStateProvider.notifier).loadNotes(keyword: value);
              },
            ),
          ),
          // 标签筛选
          _buildTagFilter(),
          // 笔记列表
          Expanded(
            child: _buildNoteList(noteState, notes),
          ),
        ],
      ),
    );
  }

  /// 构建标签筛选器
  Widget _buildTagFilter() {
    // 模拟标签数据
    final allTags = ['需求分析', '会议纪要', '技术方案', 'API设计', '后端开发', '规范'];

    return SizedBox(
      height: 50,
      child: ListView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        children: [
          ChoiceChip(
            label: const SelectableText('全部'),
            selected: _selectedTags.isEmpty,
            onSelected: (selected) {
              setState(() {
                _selectedTags = [];
              });
              ref.read(noteStateProvider.notifier).loadNotes();
            },
          ),
          const SizedBox(width: 8),
          ...allTags.map((tag) {
            return Padding(
              padding: const EdgeInsets.only(right: 8.0),
              child: ChoiceChip(
                label: SelectableText(tag),
                selected: _selectedTags.contains(tag),
                onSelected: (selected) {
                  setState(() {
                    if (selected) {
                      _selectedTags.add(tag);
                    } else {
                      _selectedTags.remove(tag);
                    }
                  });
                  ref
                      .read(noteStateProvider.notifier)
                      .loadNotes(tags: _selectedTags);
                },
              ),
            );
          }),
        ],
      ),
    );
  }

  /// 构建笔记列表
  Widget _buildNoteList(NoteState state, List<Note> notes) {
    if (state is NoteLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (state is NoteError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            SelectableText('加载失败: ${state.message}'),
            const SizedBox(height: 16),
            AdaptiveButton(
              onPressed: () {
                ref.read(noteStateProvider.notifier).loadNotes();
              },
              child: const SelectableText('重新加载'),
            ),
          ],
        ),
      );
    }

    if (notes.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.note_alt,
              size: 64,
              color: Colors.grey,
            ),
            const SizedBox(height: 16),
            SelectableText(
              '暂无笔记',
              style: Theme.of(context).textTheme.headlineSmall,
            ),
            const SizedBox(height: 8),
            const SelectableText(
              '点击右上角“+”号创建新笔记',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: () async {
        ref.read(noteStateProvider.notifier).loadNotes();
      },
      child: LayoutBuilder(
        builder: (context, constraints) {
          // 使用响应式网格布局
          return _buildResponsiveGrid(notes);
        },
      ),
    );
  }

  /// 构建响应式网格布局
  Widget _buildResponsiveGrid(List<Note> notes) {
    return ResponsiveGrid(
      spacing: 16,
      runSpacing: 16,
      children: notes.map((note) => _buildNoteCard(note)).toList(),
    );
  }

  /// 构建笔记卡片
  Widget _buildNoteCard(Note note) {
    return AdaptiveCard(
      child: InkWell(
        onTap: () {
          // 跳转到笔记详情页面
          context.push('/admin/notes/${note.id}');
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题和类型
            Row(
              children: [
                Expanded(
                  child: Text(
                    note.title,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8.0,
                    vertical: 4.0,
                  ),
                  decoration: BoxDecoration(
                    color: _getNoteTypeColor(note.noteType),
                    borderRadius: BorderRadius.circular(12.0),
                  ),
                  child: Text(
                    note.noteType.description,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),

            // 内容预览
            Text(
              note.content,
              style: const TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(height: 12),

            // 标签
            Wrap(
              spacing: 6.0,
              runSpacing: 4.0,
              children: note.tags.map((tag) {
                return Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8.0,
                    vertical: 4.0,
                  ),
                  decoration: BoxDecoration(
                    color: Colors.blue.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12.0),
                    border: Border.all(
                      color: Colors.blue.withOpacity(0.3),
                    ),
                  ),
                  child: Text(
                    tag,
                    style: const TextStyle(
                      fontSize: 12,
                      color: Colors.blue,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                );
              }).toList(),
            ),
            const SizedBox(height: 12),

            // 底部信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _formatDate(note.updateTime),
                  style: const TextStyle(
                    fontSize: 12,
                    color: Colors.grey,
                  ),
                ),
                if (note.isPublic)
                  const Icon(
                    Icons.public,
                    size: 16,
                    color: Colors.green,
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 获取笔记类型颜色
  Color _getNoteTypeColor(NoteType type) {
    switch (type) {
      case NoteType.meeting:
        return Colors.orange;
      case NoteType.solution:
        return Colors.green;
      case NoteType.issue:
        return Colors.red;
      default:
        return Colors.blue;
    }
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    final now = DateTime.now();
    final difference = now.difference(date);

    if (difference.inDays == 0) {
      return '今天 ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays == 1) {
      return '昨天 ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${date.month}-${date.day} ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
    }
  }
}
